package com.ms.p2p.service.impl;


import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.MsDateUtils;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.dao.EverydayDao;
import com.ms.p2p.dao.LoanTenderRecordDao;
import com.ms.p2p.dao.MemberAccountDao;
import com.ms.p2p.entity.account.Account;
import com.ms.p2p.entity.account.AccountRecharge;
import com.ms.p2p.entity.account.Withdraw;
import com.ms.p2p.entity.loan.Loan;
import com.ms.p2p.entity.member.Ecv;
import com.ms.p2p.entity.system.AdminLog;
import com.ms.p2p.entity.system.AdminUser;
import com.ms.p2p.enums.AccountFLow;
import com.ms.p2p.enums.AccountType;
import com.ms.p2p.provider.EvcProvider;
import com.ms.p2p.provider.MemberAccountRecordProvider;
import com.ms.p2p.provider.MemberWithDrawProvider;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class MemberAccountServiceImpl {
    protected static Logger logger = Logger.getLogger(MemberAccountServiceImpl.class);
    @Autowired
    private MemberAccountRecordServiceImpl memberAccountRecordService;

    @Autowired
    private EvcProvider ecvService;

    @Autowired
    private AdminLogServiceImpl adminLoginService;

    @Autowired
    private MemberServiceImpl memberService;


    @Autowired
    private MemberAccountRechargeServiceImpl rechargeService;

    @Autowired
    private MemberWithDrawServiceImpl memberWithDrawService;

    @Autowired
    private EverydayDao everyDayDao;

    @Autowired
    MemberAccountDao memberAccountDao;

    @Autowired
    LoanTenderRecordDao tenderDao;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public int openAccount(Account account) {
        return memberAccountDao.insert(account);

    }

    public Account findByUserId(int userId) {
        return memberAccountDao.findByUserId(userId);

    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void OperAccount(String ip,BigDecimal money, int userId, String remark,
            String type,String s){
        if(memberAccountDao.OperationAmount(type,money,userId)<=0){
            throw  new NoticeException("出现未知错误,请联系客服解决问题");
        }
        memberAccountRecordService.record(userId, money, remark, ip, type,s);
        if (type.equals("withdraw_success")) {
            String date_time = MsDateUtils.TimeStamp2Date(System.currentTimeMillis()
                    + "");
            memberAccountDao.updateEveryDayOut(date_time, money);
        }else  if (type.equals("recharge")) {
            String date_time = MsDateUtils.TimeStamp2Date(System.currentTimeMillis()
                    + "");
            memberAccountDao.updateEveryDay(date_time, money);
        }
    }



    public List<Map<String, Object>> findPager(String userId, String userName,
                                               String begin_date, String end_date, PageBean page) {
        return memberAccountDao.findPager(userId, userName, begin_date, end_date,
                page.getBegin(), page.getPageSize());
    }

    public int findCount(String userId, String userName, String begin_date,
                         String end_date) {
        return memberAccountDao.findCount(userId, userName, begin_date, end_date);
    }

    public List<Map<String, Object>> findAll(String userId, String userName,
                                             String begin_date, String end_date) {
        return memberAccountDao.findAll(userId, userName, begin_date, end_date);
    }

    public List<Map<String, Object>> geteveryday(PageBean page) {
        return everyDayDao.getList(page);
    }

    public List<Account> findlistByCollection(String collection) {
        return memberAccountDao.getCollectionList(collection);

    }


    public void CacueEvc(String evc_id, BigDecimal successAmount, Integer u_id,
                         Loan borrow) {

        Ecv ecv = ecvService.SelectByid(evc_id);
        ecvService.use(evc_id, u_id);
        if (ecv == null) {
            throw new NoticeException("红包已过期或者不存在");
        }
        if (successAmount.compareTo(ecv.getTender_money_limit()) == -1) {
            throw new NoticeException("您的有效投资金额是" + successAmount
                    + "小于红包所要求最小限额" + ecv.getTender_money_limit());
        }
        try {

        } catch (Exception e) {
            throw new NoticeException("发生系统错误");
        }
    }

    public List<Map<String, Object>> FindTG() {
        return memberAccountDao.findTG();
    }


    @Cacheable(value = "invest")
    public List<Map<String, Object>> findtenderListIndex() {

        return tenderDao.getRanks(MsDateUtils.getTimesMonthmorning(),MsDateUtils.getMonthEnd());

    }

    public List<Map<String, Object>> findtenderListPager(String time_limit, String begin_date, String end_date, PageBean page) {
        return tenderDao.findtenderListPager(time_limit, begin_date, end_date, page.getBegin(), page.getPageSize());
    }

    public List<Map<String, Object>> findCollectioListPager(String userId, String userName, String realname, String begin_date, String end_date, String is_day, PageBean page) {
        return tenderDao.findtenderColPager(userId, userName, realname, begin_date, end_date, is_day);
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void cashVerify(String ip,Withdraw withdraw,  String remark) {
        try {
            if (withdraw.getStatus() == 1) {
                OperAccount(ip,withdraw.getTotal(),withdraw.getUser_id(), "提现成功,到账金额￥" + withdraw.getTotal() + ",审核备注："
                        + remark + "。", AccountType.withdraw_success.getValue(), AccountFLow.FLOW_OUT.getValue());
            } else {
                OperAccount(ip,withdraw.getTotal(),withdraw.getUser_id(),"提现失败，备注："+remark+"",AccountType.withdraw_false.getValue(),AccountFLow.FLOW_THAW.getValue());
            }
            memberWithDrawService.update(withdraw);
        } catch (Exception ex) {
            logger.error("提现审核失败", ex);
            throw new NoticeException("提现审核失败");
        }

    }
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void rechargeVerify(AccountRecharge recharge, String header, String remoteIp, AdminUser emp,String remark,String status) {
        int result = rechargeService.updateVerify(recharge);
        if (result > 0) {
            AdminLog loginLog = new AdminLog();
            UserAgent userAgent = UserAgent.parseUserAgentString(header);
            loginLog.setDevice(userAgent.toString());
            loginLog.setIp(remoteIp);
            loginLog.setOpera_username(emp.getAdmin_name());
            loginLog.setOpera("充值");
            loginLog.setStatus(1);
            loginLog.setRemark(emp.getName()+"在"+MsDateUtils.TimeStamp2DateTime(MsDateUtils.getTime())+"给用户"+ memberService.findById(recharge.getUser_id()).getUser_name()+"充值"+ recharge.getMoney());
            loginLog.setTime(MsDateUtils.getTime());
            adminLoginService.insert(loginLog);
            if (Integer.parseInt(status) == 1) {
                String income = "订单号为："
                        + recharge.getTrade_no()
                        + "的线下充值审核通过，充值金额￥" + recharge.getMoney()
                        + "，手续费￥" + recharge.getFee() + ",到账金额￥"
                        + recharge.getAmount() + ",审核备注：" + remark
                        + "。";
                if (recharge.getPayment() == 4) {
                    income = remark;
                }
               OperAccount(remoteIp,recharge.getAmount(),recharge.getUser_id(),income, AccountType.recharge.getValue(), AccountFLow.FLOW_IN.getValue());
            }
        } else {
            throw new NoticeException("不要重复提交");
        }
    }

    public BigDecimal sumYuebao() {
        return memberAccountDao.sumYuebao();
    }
}
